# -*- coding:utf-8 -*-

# @Time    : 2023/7/30 21:07
# @Author  : zengwenjia
# @Email   : zengwenjia@lingxi.ai
# @Software: LLM_internal

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #


import asyncio
import json
import traceback
from urllib.parse import urlparse, parse_qs

import aiohttp

from common.log import logger
from db.redis.redis_service import RedisMemory

memory_cache = RedisMemory()


async def fetch(session, url, payload):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
        'Content-Type': 'text/javascript; charset=utf-8',
        'Content-Encoding': 'gzip'
    }
    async with session.get(url, params=payload, headers=headers) as response:
        return await response.text()


insurance_coverage_measure_dict = {
    "小青龙2号少儿重大疾病保险（互联网）  保终身（A款）": {
        "insurance_API": "https://www.huize.com/apps/cps/product/tryTrial?callback=jQuery1820657080322504751_1695288991677&uid=10000000&protectItemId=15229&prodId=102849&planId=106466",
        "insurance_params": "{\"\":\"10万元\",\"vesterAge\":\"1990-07-01\",\"vesterSex\":\"男\",\"insurantDate\":\"2022-07-01\",\"sex\":\"男\",\"insurantJob\":\"1-4类\",\"insurantDateLimit\":\"终身\",\"paymentType\":\"年交\",\"insureAgeLimit\":\"30年\",\"deathOrTotalDisabilityBenefits\":\"不含\",\"additionalInsuranceForMalignantTumors\":\"不含\",\"diseaseCareInsurance\":\"不含\",\"isInsure\":\"不含\",\"generalHospitalizationMedicalInsurance\":\"含\",\"hospitalDailyAmount\":\"100元\",\"policyholderExemption\":\"不含\",\"additionalRiskPeriod1\":\"终身\",\"paymentType2\":\"年交\",\"policyholdeExemptionAdditionalInsureAgeLimit\":\"不投保\",\"additionalRiskPeriod\":\"终身\",\"paymentType1\":\"年交\",\"additionalInsureAgeLimit1\":\"30年\"}"
    },
    "慧择小医仙2号医疗险  计划二": {
        "insurance_API": "https://www.huize.com/apps/cps/product/tryTrial?callback=jQuery182016999755480582546_1695177933481&uid=10000000&prodId=102299&planId=105226",
        "insurance_params": ""
    },
    "MSH精选个人全球医疗保险_全球保障": {
        "insurance_API": "https://www.huize.com/apps/cps/product/tryTrial?callback=jQuery18207762592584305645_1695265254977&uid=10000000&prodId=102641&planId=106036&protectItemId=13898",
        "insurance_params": "{\"\":\"1600万元\",\"insurantDate\":\"2007-10-01\",\"hospitalType\":\"选项二(公立私立，含昂贵医院)\",\"DeductibleAmount\":\"0元\",\"emergencyServices\":\"不含\",\"dentalResponsibility\":\"不含\",\"physicalExamination\":\"不含\",\"insurantJob\":\"1-2类\",\"insurantDateLimit\":\"1年\",\"buyCount\":\"1份\",\"insureAgeLimit\":\"趸交\",\"paymentType\":\"一次性\"}"
    },
    "大麦旗舰版A款定期寿险（互联网专属）": {
        "insurance_API": "https://www.huize.com/apps/cps/product/tryTrial?callback=jQuery182011967392250053832_1695288265911&uid=10000000&prodId=102876&planId=106504",
        "insurance_params": "{\"\":\"10万元\",\"insurantDate\":\"2000-08-08\",\"sex\":\"女\",\"city\":\"110100\",\"province\":\"110000\",\"insurantJobN\":\"其他1-6类职业\",\"haveSocialSecurity\":\"否\",\"insurantDateLimit\":\"10年\",\"paymentType\":\"年交\",\"insureAgeLimit\":\"10年\",\"isInsure\":\"不含\",\"isInsureTwo\":\"不含\",\"paymentPeriod\":\"不含\",\"isInsureThree\":\"不含\",\"healthLevel\":\"1\"}"
    },
    "i无忧2.0重大疾病保险（A款）（互联网专属）": {
        "insurance_API": "https://www.huize.com/apps/cps/product/tryTrial?callback=jQuery18209444030920934559_1695288040186&uid=10000000&prodId=102842&planId=106456&protectItemId=15182",
        "insurance_params": "{\"\":\"20万元\",\"insurantDate\":\"1995-07-13\",\"sex\":\"女\",\"city\":\"110100\",\"province\":\"110000\",\"insurantJob\":\"1-4类\",\"paymentType\":\"年交\",\"insureAgeLimit\":\"30年\",\"insurantDateLimit\":\"终身\",\"coverageSecond\":\"不含\",\"diseaseCareInsurance\":\"不含\",\"additionalInsuranceForMalignantTumors\":\"不含\",\"cardiovascularAndCerebrovascularCompensation\":\"不含\",\"deathOrTotalDisabilityBenefits\":\"不含\"}"
    },
    "小红花致夏版重大疾病保险": {
        "insurance_API": "https://www.huize.com/apps/cps/product/tryTrial?callback=jQuery18207952445931752696_1695288119837&uid=10000000&prodId=102883&planId=106512&protectItemId=15374",
        "insurance_params": "{\"\":\"5万元\",\"insurantDate\":\"2022-09-01\",\"sex\":\"女\",\"insurantJob\":\"1-6类\",\"insurantDateLimit\":\"至70岁\",\"diseaseCareInsurance\":\"含\",\"manyTimesWithSeriousIllness\":\"含\",\"additionalCompensationForMalignantTumor\":\"含\",\"cardiovascularAndCerebrovascularCompensation\":\"含\",\"paymentType\":\"年交\",\"insureAgeLimit\":\"10年\"}"
    },
    "长相安长期医疗险（20年保证续保）—个人版": {
        "insurance_API": "https://www.huize.com/apps/cps/product/tryTrial?callback=jQuery18200005287671851850195_1698653544131&uid=10000000&prodId=102752&planId=106280",
        "insurance_params": "{\"insurantDate\":\"2006-05-30\",\"sex\":\"男\",\"haveMedical\":\"有\",\"insurantDateLimit\":\"1年\",\"paymentType\":\"年交\",\"insureAgeLimit\":\"1年\",\"buyCount\":\"1份\",\"offhospitalSpecificDrugTreatment\":\"不含\",\"inpatientAllowanceInIntensiveCareUnit\":\"不含\",\"onlineConsulTationDrugFee\":\"不含\",\"outpatientAndEmergencyMedicalTreatmentForChildren\":\"不含\"}"
    },
    "华贵麦兜兜少儿重大疾病保险（互联网专属）  方案二": {
        "insurance_API": "https://www.huize.com/apps/cps/product/tryTrial?callback=jQuery182015352120195921204_1695289110602&uid=10000000&prodId=102914&planId=106564&protectItemId=15540",
        "insurance_params": "{\"\":\"100万元\",\"insurantDate\":\"2023-08-17\",\"sex\":\"男\",\"insurantJob\":\"1-6类\",\"insurantDateLimit\":\"30年\",\"paymentType\":\"年交\",\"insureAgeLimit\":\"30年\"}"
    },
    "慧择少儿门诊暖宝保（超能版）  有社保": {
        "insurance_API": "https://www.huize.com/apps/cps/product/getTrial?callback=jQuery182037513122912102714_1695124067542&uid=10000000&prodId=102368&planId=105365&_=1695124067664",
        "insurance_params": ""
    },
    "小神童3号少儿意外险  经典版": {
        "insurance_API": "https://www.huize.com/apps/cps/product/tryTrial?callback=jQuery182031367433615183327_1695289267139&uid=10000000&prodId=102319&planId=105269",
        "insurance_params": "{\"insurantDate\":\"出生满30天-17周岁\",\"insurantDateLimit\":\"1年\",\"buyCount\":\"1份\",\"isInsure\":\"不含\",\"isInsureTwo\":\"不含\"}"
    },
    "小蜜蜂3号综合意外险  经典版": {
        "insurance_API": "https://www.huize.com/apps/cps/product/getTrial?callback=jQuery18205210720721968356_1695119010192&uid=10000000&prodId=102688&planId=106127&_=1695119010306",
        "insurance_params": ""
    },
    "慧择铁甲小保2号少儿长期医疗险  计划二": {
        "insurance_API": "https://www.huize.com/apps/cps/product/tryTrial?callback=jQuery182014144506317515626_1695288600261&uid=10000000&prodId=102581&planId=105887",
        "insurance_params": "{\"insurantDate\":\"2022-05-21\",\"sex\":\"男\",\"haveSocialSecurity\":\"有\",\"paymentType\":\"年交\",\"insureAgeLimit\":\"1年\",\"insurantDateLimit\":\"1年\",\"buyCount\":\"1份\",\"isInsure\":\"不含\"}"
    },
    "臻爱无忧医疗保险（互联网专属）_特需版计划一": {
        "insurance_API": "https://www.huize.com/apps/cps/product/tryTrial?callback=jQuery18207320070710684987_1695281595621&uid=10000000&prodId=102601&planId=105926",
        "insurance_params": "{\"insurantDate\":\"2021-07-07\",\"sex\":\"男\",\"buyCount\":\"1份\",\"insurantJob\":\"1-6类\",\"insurantDateLimit\":\"1年\",\"paymentType\":\"一次性\",\"insureAgeLimit\":\"趸交\",\"haveMedical\":\"有\",\"isInsure\":\"有\",\"malignantSpecialDrugsOutsideHospital\":\"含\",\"malignantTumorSevereCareInsurance\":\"含\"}"
    },
    "医享无忧惠享版百万医疗险—个人版": {
        "insurance_API": "https://www.huize.com/apps/cps/product/tryTrial?callback=jQuery182008453232410985123_1695299848647&uid=10000000&prodId=102601&planId=105926",
        "insurance_params": "{\"insurantDate\":\"2021-07-07\",\"sex\":\"男\",\"buyCount\":\"1份\",\"insurantJob\":\"1-6类\",\"insurantDateLimit\":\"1年\",\"paymentType\":\"一次性\",\"insureAgeLimit\":\"趸交\",\"haveMedical\":\"有\",\"isInsure\":\"有\",\"malignantSpecialDrugsOutsideHospital\":\"不含\",\"malignantTumorSevereCareInsurance\":\"不含\"}"
    }
}

item_dict = {
    "特定心脑血管疾病扩展保险金": "cardiovascularAndCerebrovascularCompensation",
    "投保地区": "city",
    "意外医疗扩展": "isInsureTwo",
    "附加豁免保费A款缴费年限": "policyholdeExemptionAdditionalInsureAgeLimit",
    "特定心脑血管疾病额外保险金": "cardiovascularAndCerebrovascularCompensation",
    "缴费年限": "insureAgeLimit",
    "门诊保障": "emergencyServices",
    "（可选）附加麦芽糖失能收入损失保险金": "isInsureThree",
    "有无基本医疗保险": "haveSocialSecurity",
    "住院保障免赔额": "DeductibleAmount",
    "被保险人出生日期": "insurantDate",
    "重大疾病保障": "isInsureThree",
    "特定药品保障": "isInsure",
    "投保人性别": "vesterSex",
    "被保险人职业": "insurantJobN",
    "恶性肿瘤—重度额外给付保险金": "additionalInsuranceForMalignantTumors",
    "院外恶性肿瘤特定药品费用医疗保险金": "offhospitalSpecificDrugTreatment",
    "（可选）水陆公共交通意外身故或身体全残保险金": "isInsureTwo",
    "身故保险金或全残保险金": "deathOrTotalDisabilityBenefits",
    "是否有医保": "haveMedical",
    "缴费类型": "paymentType",
    "被保险人性别": "sex",
    "疾病关爱保险金": "diseaseCareInsurance",
    "住院医疗保险": "isInsure",
    "承保职业": "insurantJob",
    "门急诊医疗保障": "isInsureTwo",
    "住院医疗日额": "hospitalDailyAmount",
    "疾病关爱保险金（前30年）": "diseaseCareInsurance",
    "省": "province",
    "恶性肿瘤—重度关爱保险金": "malignantTumorSevereCareInsurance",
    "疾病关爱金": "diseaseCareInsurance",
    "意外骨折/关节脱位保险金": "isInsure",
    "乐医享在线问诊医疗保险金": "onlineConsulTationDrugFee",
    "重大疾病扩展保险金": "manyTimesWithSeriousIllness",
    "附加豁免保费A款重大疾病保险": "policyholderExemption",
    "投保人年龄": "vesterAge",
    "被保险人有无惠民保": "isInsure",
    "牙科保障": "dentalResponsibility",
    "购买份数": "buyCount",
    "附加住院定额给付A款医疗保险": "generalHospitalizationMedicalInsurance",
    "重度恶性肿瘤扩展保险金": "additionalCompensationForMalignantTumor",
    "保障期限": "insurantDateLimit",
    "最高给付期限": "paymentPeriod",
    "疾病关爱保险金（60周岁前）": "isInsure",
    "（可选）航空意外身故或身体全残保险金": "isInsure",
    "恶性肿瘤—重度院外特定药品保险金": "malignantSpecialDrugsOutsideHospital",
    "是否有社保": "haveSocialSecurity",
    "恶性肿瘤-轻度/重度、原位癌额外保险金": "additionalInsuranceForMalignantTumors",
    "体检保障": "physicalExamination",
    "第二次重大疾病保险金": "coverageSecond",
    "住院医疗免赔额": "DeductibleAmount",
    "重症监护病房住院津贴保险金": "inpatientAllowanceInIntensiveCareUnit",
    "医院类型": "hospitalType",
    "门急诊免赔额": "DeductibleAmountTwo"
}


def round_up_to_nearest(number):
    try:
        number = float(number)
        if number.is_integer():
            number = int(number)
        num_length = len(str(number))

        if num_length <= 3:
            target_position = 10
        elif num_length == 4:
            target_position = 100
        elif num_length == 5:
            target_position = 1000
        elif num_length == 6:
            target_position = 10000
        else:
            return number  # 超过六位数的情况，直接返回原值

        base = target_position
        remainder = number % base
        if remainder == 0:
            return number
        else:
            return number + base - remainder
    except:
        return number


async def get_insurance_premium_url(url, payload, cookies):
    try:
        async with aiohttp.ClientSession(cookies=cookies) as session:
            html = await fetch(session,
                               url, payload=payload)
            start_index = html.index("{")
            json_str = html[start_index:]
            json_str = json_str[:-2]
            result = json.loads(json_str)
            preminum = result['data']["preminum"]
            print("保费测算结果===" + preminum)
            return preminum
    except Exception:
        print("系统错误")


def extract_ids_from_url(url):
    try:
        parsed_url = urlparse(url)

        # 获取查询参数
        query_params = parse_qs(parsed_url.query)

        # 获取prodId和planId参数值
        if 'prodId' in query_params and 'planId' in query_params:
            prodId = query_params.get("prodId", [''])[0]
            planId = query_params.get("planId", [''])[0]
            protectItemId = query_params.get("protectItemId", [''])[0]

            return prodId, planId, protectItemId
        else:
            return None, None, None
    except Exception as e:
        print("提取参数时发生错误:", str(e))
        return None, None


def update_primary_dict_by_other(source, target):
    for key, value in source.items():
        # 检查键是否也在字典B中存在
        if key in target:
            # 如果存在，用字典B中的值替换字典A中的值
            source[key] = target[key]

    return source


def replace_dict_keys_with_redis_values(redis_memory, insurance_name, data_dict):
    updated_dict = {}
    # 循环遍历字典中的每个键
    for chinese_key in data_dict.keys():
        # 查询Redis中的值
        redis_value = redis_memory.get_memory("product_dict:" + insurance_name, chinese_key)

        # 如果找到对应的值，替换字典中的键
        if redis_value is not None:
            updated_dict[redis_value] = data_dict[chinese_key]
        elif chinese_key == '基本保额':
            updated_dict[''] = data_dict[chinese_key]
        else:
            # 如果未找到对应值，则保留原始键
            updated_dict[chinese_key] = data_dict[chinese_key]

    return updated_dict


async def premium_calculate(insurance_name, user_info, insurance_need_cn: dict):
    preminum = ''
    try:
        # redis读取配置文件
        product_info = memory_cache.get_memory("insurance_product_cn", insurance_name)

        if product_info:
            url = product_info.get("insurance_API")

            need_from_user_info = {}
            # 按照不同的保费测算企业更改参数映射
            if 'huize' in url:
                need_from_user_info = userinfo_2_other_company(user_info, 'huize')
            elif 'xiaoyusan' in url:
                need_from_user_info = userinfo_2_other_company(user_info, 'xiaoyusan')
            elif 'fhrons' in url:
                return 1250

            insurance_need_cn.update(need_from_user_info)

            # 用获取到的用户需求信息替换redis里存储的默认的信息
            updated_dict = replace_dict_keys_with_redis_values(memory_cache, insurance_name, insurance_need_cn)

            insurance_params = product_info.get("insurance_params", "")

            payload = {}
            if insurance_params:
                insurance_params = json.loads(insurance_params)
                insurance_params = update_primary_dict_by_other(insurance_params, updated_dict)
                product_id, productPlanId, protectItemId = extract_ids_from_url(url)

                # 遍历key拼接请求参数
                genes = []
                for key in insurance_params:
                    value = insurance_params.get(key, "")
                    if key == '' and protectItemId:
                        value = insurance_params.get(key, "")
                        genes_item = {
                            "sort": 1,
                            "protectItemId": int(protectItemId),
                            "key": "",
                            "value": value
                        }
                    else:
                        genes_item = {
                            "sort": 1,
                            "protectItemId": "",
                            "key": key,
                            "value": value
                        }
                    genes.append(genes_item)

                genes = json.dumps(genes, ensure_ascii=False, indent=4)

                restrictGeneParams_value = '{"productId":"' + product_id + '","productPlanId":"' + productPlanId + '","genes":' + genes + '}'

                payload = {'restrictGeneParams': restrictGeneParams_value.replace("\n", "").replace(" ", "")}

            logger.info(f"调用接口计算参数为:{payload}")
            cookies = {'acw_tc': '2f6a1fc916907294756776161e6d00ef970338155729a78d1e6fea17ec1456'}  # 设置cookie
            preminum = await get_insurance_premium_url(url, payload, cookies)
    except Exception:
        logger.error(traceback.format_exc())
        pass
    return preminum


def userinfo_2_other_company(user_info, product_company):
    need_from_user_info = {}
    if product_company and user_info and 'huize' == product_company:
        need_from_user_info['被保险人出生日期'] = user_info.get('birth_date', '2000-01-01')
        need_from_user_info['被保险人性别'] = user_info.get('sex', '男')
    return need_from_user_info


if __name__ == '__main__':
    insurance_name = "慧择小医仙2号医疗险  计划二"

    insurance_need_cn = {
        # "门急诊医疗保障": "10000元",
        # "被保险人出生日期": "1998-07-01",
        # "被保险人性别": "男",
        # "缴费类型": "年交",
        # "缴费年限": "30年",
        # "基本保额": "22万元",
        # "身故保险金或全残保险金": "不含",
        # "恶性肿瘤—重度额外给付保险金": "不含",
        # "疾病关爱保险金（前30年）": "不含",
        # "疾病关爱保险金（60周岁前）": "不含",
        # "附加住院定额给付A款医疗保险": "含",
        # "住院医疗日额": "100元",
        # "附加豁免保费A款重大疾病保险": "含",
        # "附加豁免保费A款缴费年限": "29年",
    }
    # x = asyncio.run(premium_calculate(insurance_name, {''}, insurance_need_cn))
    print(x)
